// 全局变量
let currentVideoIndex = 0;
let videoList = [];
let videoElement = null;
let isFullscreen = false;

// 初始化
document.addEventListener('DOMContentLoaded', function() {
    initializeElements();
    initializeEventListeners();
    loadVideoList().then(() => {
        loadVideo();
    });
});

// 初始化元素
function initializeElements() {
    videoElement = document.getElementById('videoElement');
}

// 初始化事件监听器
function initializeEventListeners() {
    // 视频事件
    videoElement.addEventListener('loadedmetadata', onVideoLoaded);
    videoElement.addEventListener('timeupdate', updateProgress);
    videoElement.addEventListener('ended', onVideoEnded);
    videoElement.addEventListener('error', onVideoError);
    videoElement.addEventListener('waiting', function() { showLoading(true); });
    videoElement.addEventListener('canplay', function() { showLoading(false); });
    
    // 全屏事件和按钮
    document.addEventListener('fullscreenchange', onFullscreenChange);
    document.getElementById('fullscreen').addEventListener('click', toggleFullscreen);
    
    // 返回按钮
    initBackButton();
    
    // 播放列表按钮
    document.getElementById('playlistBtn').addEventListener('click', togglePlaylist);
    document.getElementById('closePlaylist').addEventListener('click', togglePlaylist);
    
    // 上一个/下一个视频按钮
    document.getElementById('prevVideo').addEventListener('click', playPreviousVideo);
    document.getElementById('nextVideo').addEventListener('click', playNextVideo);
    
    // 设置面板
    document.getElementById('settings').addEventListener('click', toggleSettingsPanel);
    document.getElementById('closeSettings').addEventListener('click', toggleSettingsPanel);
    
    // 播放设置变化
    document.getElementById('playbackSpeed').addEventListener('change', changePlaybackSpeed);
    document.getElementById('videoQuality').addEventListener('change', changeVideoQuality);
    document.getElementById('subtitles').addEventListener('change', toggleSubtitles);
}

// 切换设置面板
function toggleSettingsPanel() {
    const settingsPanel = document.getElementById('settingsPanel');
    settingsPanel.classList.toggle('open');
}

// 更改播放速度
function changePlaybackSpeed() {
    const playbackSpeed = parseFloat(document.getElementById('playbackSpeed').value);
    videoElement.playbackRate = playbackSpeed;
}

// 更改视频质量
function changeVideoQuality() {
    const quality = document.getElementById('videoQuality').value;
    // 这里可以实现不同质量的切换逻辑
    // 对于本项目，主要是演示功能
    console.log('切换视频质量至:', quality);
    // 实际项目中，可能需要根据quality值切换不同的视频源
}

// 切换字幕
function toggleSubtitles() {
    const subtitlesEnabled = document.getElementById('subtitles').value === 'on';
    // 这里可以实现字幕切换逻辑
    console.log('字幕:', subtitlesEnabled ? '开启' : '关闭');
}

// 加载视频列表
async function loadVideoList() {
    try {
        const response = await fetch('/api/files/videos');
        videoList = await response.json();
        
        if (videoList.length === 0) {
            showNoVideosMessage();
        } else {
            // 更新播放列表
            updatePlaylist();
        }
    } catch (error) {
        console.error('Error loading video list:', error);
        showNoVideosMessage();
    }
}

// 显示无视频消息
function showNoVideosMessage() {
    const videoPlayer = document.getElementById('videoPlayer');
    videoPlayer.innerHTML = `
        <div class="no-videos">
            <h2>暂无视频文件</h2>
            <p>请联系管理员上传视频文件</p>
            <button onclick="goBack()" class="back-btn">返回首页</button>
        </div>
    `;
}

// 加载视频
function loadVideo() {
    const urlParams = new URLSearchParams(window.location.search);
    const file = urlParams.get('file');
    const chapter = urlParams.get('chapter');
    const startTime = urlParams.get('start');
    const endTime = urlParams.get('end');
    
    if (file) {
        // 解码URL编码的文件路径
        const decodedFile = decodeURIComponent(file);
        // 如果指定了文件，找到对应的视频
        const videoIndex = videoList.findIndex(v => v.path === decodedFile);
        if (videoIndex !== -1) {
            currentVideoIndex = videoIndex;
        }
    } else if (chapter) {
        // 如果指定了章节，找到对应的视频
        const videoIndex = videoList.findIndex(v => v.name.includes(`Chapter${chapter}`) || v.name.includes(`第${chapter}章`));
        if (videoIndex !== -1) {
            currentVideoIndex = videoIndex;
        }
    }
    
    if (videoList.length > 0) {
        const video = videoList[currentVideoIndex];
        playVideo(video, startTime, endTime);
    }
}

// 播放视频
function playVideo(video, startTime = null, endTime = null) {
    showLoading(true);
    
    // 确保视频路径正确
    let videoPath = video.path;
    // 如果路径不是以/开头，添加/以确保正确的相对路径
    if (!videoPath.startsWith('/')) {
        videoPath = '/' + videoPath;
    }
    
    // 设置视频源
    videoElement.src = videoPath;
    
    // 尝试播放视频
    videoElement.load();
    
    // 设置视频信息
    document.getElementById('videoTitle').textContent = '视频播放器';
    document.getElementById('videoName').textContent = video.name;
    document.getElementById('videoDescription').textContent = `文件大小: ${(video.size / 1024 / 1024).toFixed(2)} MB`;
    
    // 更新当前视频索引
    currentVideoIndex = videoList.findIndex(v => v.path === video.path);
    updateVideoInfo();
    
    // 更新播放列表显示
    updatePlaylist();
    
    // 如果指定了开始时间，设置播放位置
    if (startTime) {
        videoElement.addEventListener('loadedmetadata', function() {
            videoElement.currentTime = parseInt(startTime) * 60; // 转换为秒
            videoElement.play(); // 开始播放
        }, { once: true });
    } else {
        // 自动播放视频
        videoElement.addEventListener('canplaythrough', function() {
            videoElement.play();
        }, { once: true });
    }
    
    // 如果指定了结束时间，监听时间更新
    if (endTime) {
        const endTimeSeconds = parseInt(endTime) * 60;
        videoElement.addEventListener('timeupdate', function() {
            if (videoElement.currentTime >= endTimeSeconds) {
                videoElement.pause();
            }
        });
    }
}

// 视频加载完成
function onVideoLoaded() {
    showLoading(false);
    
    const duration = videoElement.duration;
    document.getElementById('totalTime').textContent = formatTime(duration);
    document.getElementById('videoDuration').textContent = `时长: ${formatTime(duration)}`;
    
    // 设置默认音量
    videoElement.volume = 0.7;
    updateVolumeDisplay();
}

// 视频播放结束
function onVideoEnded() {
    // 自动播放下一个视频
    if (currentVideoIndex < videoList.length - 1) {
        playNextVideo();
    }
}

// 视频错误
function onVideoError() {
    showLoading(false);
    const errorMessage = document.getElementById('errorMessage');
    
    // 显示更详细的错误信息
    let errorDetails = '无法加载视频文件';
    if (videoElement.error) {
        switch (videoElement.error.code) {
            case MediaError.MEDIA_ERR_ABORTED:
                errorDetails = '视频加载被用户中止';
                break;
            case MediaError.MEDIA_ERR_NETWORK:
                errorDetails = '网络错误导致视频加载失败';
                break;
            case MediaError.MEDIA_ERR_DECODE:
                errorDetails = '视频解码错误';
                break;
            case MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED:
                errorDetails = '不支持的视频格式或编解码器';
                break;
            default:
                errorDetails = '未知错误导致视频加载失败';
                break;
        }
    }
    
    // 更新错误信息并显示
    errorMessage.querySelector('p').textContent = errorDetails;
    errorMessage.style.display = 'block';
}

// 播放/暂停
function togglePlayPause() {
    if (videoElement.paused) {
        videoElement.play();
        document.getElementById('playPause').textContent = '⏸';
    } else {
        videoElement.pause();
        document.getElementById('playPause').textContent = '▶';
    }
}

// 快退
function rewind() {
    videoElement.currentTime = Math.max(0, videoElement.currentTime - 10);
}

// 快进
function fastForward() {
    videoElement.currentTime = Math.min(videoElement.duration, videoElement.currentTime + 10);
}

// 静音/取消静音
function toggleMute() {
    videoElement.muted = !videoElement.muted;
    const volumeBtn = document.getElementById('volumeBtn');
    volumeBtn.textContent = videoElement.muted ? '🔇' : '🔊';
}

// 设置音量
function setVolume(e) {
    const rect = e.currentTarget.getBoundingClientRect();
    const x = e.clientX - rect.left;
    const volume = x / rect.width;
    
    videoElement.volume = Math.max(0, Math.min(1, volume));
    videoElement.muted = false;
    
    updateVolumeDisplay();
}

// 更新音量显示
function updateVolumeDisplay() {
    const volumeFill = document.getElementById('volumeFill');
    const volumeBtn = document.getElementById('volumeBtn');
    
    const volume = videoElement.muted ? 0 : videoElement.volume;
    volumeFill.style.width = (volume * 100) + '%';
    volumeBtn.textContent = volume === 0 ? '🔇' : volume < 0.5 ? '🔉' : '🔊';
}

// 跳转到指定位置
function seekTo(e) {
    const rect = e.currentTarget.getBoundingClientRect();
    const x = e.clientX - rect.left;
    const progress = x / rect.width;
    
    videoElement.currentTime = progress * videoElement.duration;
}

// 更新进度条
function updateProgress() {
    const progressFill = document.getElementById('progressFill');
    const progressHandle = document.getElementById('progressHandle');
    const currentTimeSpan = document.getElementById('currentTime');
    
    if (videoElement.duration) {
        const progress = videoElement.currentTime / videoElement.duration;
        progressFill.style.width = (progress * 100) + '%';
        progressHandle.style.left = (progress * 100) + '%';
        currentTimeSpan.textContent = formatTime(videoElement.currentTime);
    }
}

// 格式化时间
function formatTime(seconds) {
    const minutes = Math.floor(seconds / 60);
    const remainingSeconds = Math.floor(seconds % 60);
    return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`;
}

// 播放上一个视频
function playPreviousVideo() {
    if (currentVideoIndex > 0) {
        currentVideoIndex--;
        playVideo(videoList[currentVideoIndex]);
    }
}

// 播放下一个视频
function playNextVideo() {
    if (currentVideoIndex < videoList.length - 1) {
        currentVideoIndex++;
        playVideo(videoList[currentVideoIndex]);
    }
}

// 切换播放列表
function togglePlaylist() {
    const playlistPanel = document.getElementById('playlistPanel');
    playlistPanel.classList.toggle('open');
}

// 更新播放列表
function updatePlaylist() {
    const playlistContent = document.getElementById('playlistContent');
    
    playlistContent.innerHTML = videoList.map((video, index) => `
        <div class="playlist-item ${index === currentVideoIndex ? 'active' : ''}" 
             onclick="playVideoByIndex(${index})">
            <div class="playlist-item-info">
                <h4>${video.name}</h4>
                <p>${(video.size / 1024 / 1024).toFixed(2)} MB</p>
            </div>
            <div class="playlist-item-status">
                ${index === currentVideoIndex ? '▶' : ''}
            </div>
        </div>
    `).join('');
}

// 通过索引播放视频
function playVideoByIndex(index) {
    if (index >= 0 && index < videoList.length) {
        currentVideoIndex = index;
        playVideo(videoList[index]);
        updatePlaylist();
    }
}

// 更新视频信息
function updateVideoInfo() {
    document.getElementById('currentVideo').textContent = currentVideoIndex + 1;
    document.getElementById('totalVideos').textContent = videoList.length;
}

// 显示/隐藏加载指示器
function showLoading(show) {
    const loadingIndicator = document.getElementById('loadingIndicator');
    const errorMessage = document.getElementById('errorMessage');
    
    if (show) {
        loadingIndicator.style.display = 'flex';
        errorMessage.style.display = 'none';
    } else {
        loadingIndicator.style.display = 'none';
    }
}

// 切换全屏
function toggleFullscreen() {
    if (!isFullscreen) {
        if (videoElement.requestFullscreen) {
            videoElement.requestFullscreen();
        } else if (videoElement.webkitRequestFullscreen) {
            videoElement.webkitRequestFullscreen();
        } else if (videoElement.msRequestFullscreen) {
            videoElement.msRequestFullscreen();
        }
    } else {
        if (document.exitFullscreen) {
            document.exitFullscreen();
        } else if (document.webkitExitFullscreen) {
            document.webkitExitFullscreen();
        } else if (document.msExitFullscreen) {
            document.msExitFullscreen();
        }
    }
}

// 全屏状态改变
function onFullscreenChange() {
    isFullscreen = !!document.fullscreenElement;
}

// 切换设置面板
function toggleSettingsPanel() {
    const settingsPanel = document.getElementById('settingsPanel');
    settingsPanel.classList.toggle('open');
}

// 更改播放速度
function changePlaybackSpeed() {
    const playbackSpeed = parseFloat(document.getElementById('playbackSpeed').value);
    videoElement.playbackRate = playbackSpeed;
}

// 更改视频质量
function changeVideoQuality() {
    const quality = document.getElementById('videoQuality').value;
    // 这里可以实现不同质量的切换逻辑
    // 对于本项目，主要是演示功能
    console.log('切换视频质量至:', quality);
    // 实际项目中，可能需要根据quality值切换不同的视频源
}

// 切换字幕
function toggleSubtitles() {
    const subtitlesEnabled = document.getElementById('subtitles').value === 'on';
    // 这里可以实现字幕切换逻辑
    console.log('字幕:', subtitlesEnabled ? '开启' : '关闭');
}

// 键盘快捷键
function handleKeyboard(e) {
    switch (e.key) {
        case ' ':
            e.preventDefault();
            togglePlayPause();
            break;
        case 'ArrowLeft':
            e.preventDefault();
            rewind();
            break;
        case 'ArrowRight':
            e.preventDefault();
            fastForward();
            break;
        case 'ArrowUp':
            e.preventDefault();
            videoElement.volume = Math.min(1, videoElement.volume + 0.1);
            updateVolumeDisplay();
            break;
        case 'ArrowDown':
            e.preventDefault();
            videoElement.volume = Math.max(0, videoElement.volume - 0.1);
            updateVolumeDisplay();
            break;
        case 'f':
        case 'F':
            toggleFullscreen();
            break;
        case 'm':
        case 'M':
            toggleMute();
            break;
    }
}

// 返回首页
function goBack() {
    window.location.href = '/';
}

// 初始化返回按钮事件监听器
function initBackButton() {
    const backBtn = document.getElementById('backBtn');
    if (backBtn) {
        backBtn.addEventListener('click', goBack);
    }
}
